//
//  SYAnsToolbar.m
//  ChatDemo-UI2.0
//
//  Created by zz on 16/7/8.
//  Copyright © 2016年 zz. All rights reserved.
//

static BOOL isZero;

#import "SYAnsToolbar.h"

@interface SYAnsToolbar()<UITextViewDelegate>
{
    CGFloat _previousTextViewContentHeight;//上一次inputTextView的contentSize.height
}

@property (strong, nonatomic) UIView *toolbarView;

@property (strong, nonatomic) UIImageView *backgroundImageView;
@property (strong, nonatomic) UIImageView *toolbarBackgroundImageView;

@end

@implementation SYAnsToolbar

-(instancetype)initWithFrame:(CGRect)frame{
    
    if (frame.size.height < ASKTOOLBARHEIGHT) {
        
        frame.size.height = ASKTOOLBARHEIGHT;
    }
    
    self = [super initWithFrame:frame];
    
    
    isZero = _canAnswer;
    
    if (self) {
        
        [self setupConfigure];
    }
    
    
    
    return self;
}

- (void)setFrame:(CGRect)frame
{
    if (frame.size.height < (ASKTopMargin * 2 + ASKINPUTTEXTVIEWHEIGHT)) {
        frame.size.height = ASKTopMargin * 2 + ASKINPUTTEXTVIEWHEIGHT;
    }
    [super setFrame:frame];
}


-(void)setupConfigure{

    self.maxTextInputViewHeight = ASKMAXINPUTHEIGHT;
    
    self.backgroundImageView.image = [[UIImage imageNamed:@"messageToolbarBg"] stretchableImageWithLeftCapWidth:0.5 topCapHeight:10];
    [self addSubview:self.backgroundImageView];
    
    self.toolbarView.frame = CGRectMake(0, 0, self.frame.size.width, 2 * ASKTopMargin + ASKINPUTTEXTVIEWHEIGHT);
    self.toolbarBackgroundImageView.frame = self.toolbarView.bounds;
    self.toolbarView.userInteractionEnabled = YES;
    [self.toolbarView addSubview:self.toolbarBackgroundImageView];
    [self addSubview:self.toolbarView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

-(void)willMoveToSuperview:(UIView *)newSuperview{
    
    if (newSuperview) {
        [self setupSubviews];
    }
    [super willMoveToSuperview:newSuperview];
}

- (void)setupSubviews{
    
    
    //CGFloat width = SCREENWIDTH - 121;
    //self.inputTextView = [[XHMessageTextView alloc] initWithFrame:CGRectMake(42, ASKTopMargin, width, ASKINPUTTEXTVIEWHEIGHT)];
    CGFloat width = SCREENWIDTH - 91;
    self.inputTextView = [[XHMessageTextView alloc] init];
    
    if (_needSendButton) {
        
        _inputTextView.frame =CGRectMake(12+32, ASKTopMargin, width-32, ASKINPUTTEXTVIEWHEIGHT);
        _inputTextView.placeHolder = @"请输入答案";
    }else
    {
        _inputTextView.frame =CGRectMake(12, ASKTopMargin, width, ASKINPUTTEXTVIEWHEIGHT);
        _inputTextView.placeHolder = @"请在此输入您的评论";
    }
    _inputTextView.scrollEnabled = YES;
    _inputTextView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    _inputTextView.returnKeyType = UIReturnKeySend;
    
    _inputTextView.delegate = self;
    _inputTextView.backgroundColor = [UIColor clearColor];
    _inputTextView.layer.borderColor = [UIColor colorWithWhite:0.8f alpha:1.0f].CGColor;
    _inputTextView.layer.borderWidth = 0.65f;
    _inputTextView.layer.cornerRadius = 6.0f;
    _inputTextView.enablesReturnKeyAutomatically=YES;
    _previousTextViewContentHeight = [self getTextViewContentH:_inputTextView];
    
    self.photoButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 34, 40)];
    self.photoButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
    [self.photoButton addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.photoButton.tag = 100;
    [self.photoButton setImage:[UIImage imageNamed:@"carmer_content_"] forState:UIControlStateNormal];
    self.photoButton.userInteractionEnabled = YES;
    
    self.sendButton = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_inputTextView.frame)+12, 10, 55, 30)];
    self.sendButton.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin;
    [self.sendButton setBackgroundColor:RGBCOLOR(57, 173, 255)];
    [self.sendButton setTitle:@"发送" forState:UIControlStateNormal];
    [self.sendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.sendButton.titleLabel.font = [UIFont systemFontOfSize:17];
    self.sendButton.layer.cornerRadius = 4;
    self.sendButton.tag = 20;
    [self.sendButton addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.toolbarView addSubview:self.inputTextView];
    
    NSLog(@"self.toolbarView.subviews=%@",self.toolbarView.subviews);
    
    if (_needSendButton) {
        
        [self.toolbarView addSubview:self.photoButton];
        [self.toolbarView addSubview:self.sendButton];
    }else
    {
        [self.toolbarView addSubview:self.sendButton];
    }
}

- (CGFloat)getTextViewContentH:(UITextView *)textView
{
    
    return ceilf([textView sizeThatFits:textView.frame.size].height);
}


#pragma mark -getter
-(UIView *)toolbarView{
    
    if (_toolbarView == nil) {
        _toolbarView = [[UIView alloc] init];
        _toolbarView.backgroundColor = [UIColor clearColor];
    }
    return _toolbarView;
}

- (UIImageView *)backgroundImageView
{
    if (_backgroundImageView == nil) {
        _backgroundImageView = [[UIImageView alloc] initWithFrame:self.bounds];
        _backgroundImageView.backgroundColor = [UIColor clearColor];
        _backgroundImageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _backgroundImageView.userInteractionEnabled = YES;
    }
    
    return _backgroundImageView;
}

- (UIImageView *)toolbarBackgroundImageView
{
    if (_toolbarBackgroundImageView == nil) {
        _toolbarBackgroundImageView = [[UIImageView alloc] init];
        _toolbarBackgroundImageView.backgroundColor = [UIColor clearColor];
        _toolbarBackgroundImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _toolbarBackgroundImageView.userInteractionEnabled = YES;
    }
    
    return _toolbarBackgroundImageView;
}

#pragma mark -点击事件
-(void)btnClick:(UIButton *)sender{
    
    if (sender.tag == 20) {  //发送
        
        if ([_delegate respondsToSelector:@selector(didSendText:)]) {
            
            [_delegate didSendText:_inputTextView.text];
            //_inputTextView.text = @"";
            [self willShowInputTextViewToHeight:[self getTextViewContentH:self.inputTextView]];
        }
    }else if (sender.tag == 100)//选择照片
    {
        
        if ([_delegate respondsToSelector:@selector(chooseImages)]) {
            
            [_delegate chooseImages];

        }
    }
}

-(void)keyboardWillChangeFrame:(NSNotification *)noti{
    
    NSDictionary *userinfo = noti.userInfo;
    
    CGRect endFrame = [userinfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect beginFrame = [userinfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGFloat duration = [userinfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [userinfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    void(^animations)() = ^{
    
        [self willShowKeyboardFromFrame:beginFrame toFrame:endFrame];
    };
    
    void(^completations)(BOOL) = ^(BOOL finished){
        
        
    };
    
    [UIView animateWithDuration:duration delay:0.0f options:(curve << 16 | UIViewAnimationOptionBeginFromCurrentState) animations:animations completion:completations];
}

-(void)willShowKeyboardFromFrame:(CGRect)beginFrame toFrame:(CGRect)toFrame{
    
    if (beginFrame.origin.y == SCREENHEIGH){
        
        self.sendButton.userInteractionEnabled=YES;
        
        [self willShowBottomHeight:toFrame.size.height];
        
    }else if (toFrame.origin.y == SCREENHEIGH){
        
        [self willShowBottomHeight:0];
    }else{
        
        [self willShowBottomHeight:toFrame.size.height];
    }
    
}

- (void)willShowBottomHeight:(CGFloat)bottomHeight{
    
    CGRect fromFrame = self.frame;
    CGFloat toHeight = self.toolbarView.frame.size.height + bottomHeight;
    CGRect toFrame = CGRectMake(fromFrame.origin.x, fromFrame.origin.y + (fromFrame.size.height - toHeight), fromFrame.size.width, toHeight);
    
    if(bottomHeight == 0 && self.frame.size.height == self.toolbarView.frame.size.height)
    {
        return;
    }
    
    self.frame = toFrame;
    
    if (_delegate && [_delegate respondsToSelector:@selector(didChangeFrameToheight:)]) {
        [_delegate didChangeFrameToheight:toHeight];
    }

}

#pragma mark - UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    [textView becomeFirstResponder];
    
    if ([self.delegate respondsToSelector:@selector(inputTextViewDidBeginEditing:)]) {
        [self.delegate inputTextViewDidBeginEditing:self.inputTextView];
    }
}
-(void)textViewDidChangeSelection:(UITextView *)textView
{
    [textView becomeFirstResponder];
    
    if ([self.delegate respondsToSelector:@selector(inputTextViewDidChangeSelection:)]) {
        [self.delegate inputTextViewDidChangeSelection:self.inputTextView];
    }
    
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
    [textView resignFirstResponder];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
        if ([text isEqualToString:@"\n"]) {
                
            if ([self.delegate respondsToSelector:@selector(didSendText:)]) {
                [self.delegate didSendText:textView.text];
                //self.inputTextView.text = @"";
                [self willShowInputTextViewToHeight:[self getTextViewContentH:self.inputTextView]];
            }

            return NO;
        }
    

    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    [self willShowInputTextViewToHeight:[self getTextViewContentH:textView]];
}


- (void)willShowInputTextViewToHeight:(CGFloat)toHeight
{
    if (toHeight < ASKINPUTTEXTVIEWHEIGHT) {
        toHeight = ASKINPUTTEXTVIEWHEIGHT;
    }
    if (toHeight > self.maxTextInputViewHeight) {
        toHeight = self.maxTextInputViewHeight;
    }
    
    if (toHeight == _previousTextViewContentHeight)
    {
        return;
    }
    else{
        CGFloat changeHeight = toHeight - _previousTextViewContentHeight;
        
        CGRect rect = self.frame;
        rect.size.height += changeHeight;
        rect.origin.y -= changeHeight;
        self.frame = rect;
        
        rect = self.toolbarView.frame;
        rect.size.height += changeHeight;
        self.toolbarView.frame = rect;
        

        //[self.inputTextView setContentOffset:CGPointMake(0.0f, (self.inputTextView.contentSize.height - self.inputTextView.frame.size.height) / 2) animated:YES];
        
        _previousTextViewContentHeight = toHeight;
        
        if (_delegate && [_delegate respondsToSelector:@selector(didChangeFrameToheight:)]){
            
            [_delegate didChangeFrameToheight:self.frame.size.height];
        }
    }
}


- (BOOL)endEditing:(BOOL)force
{
    BOOL result = [super endEditing:force];
    
    
    return result;
}

-(void)setCanAnswer:(BOOL)canAnswer{
    
    isZero = canAnswer;
}

//返回高度
+(CGFloat)defaultHeightWithCanAnswer:(BOOL)canAnswer{
    
    if (!canAnswer) {
        
        return 0;
    }
    
    return ASKTopMargin * 2 + ASKINPUTTEXTVIEWHEIGHT;
}

@end
